import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

from data.datamodel import Aisle
import settings

class AddAisleHandler(webapp.RequestHandler):
    def post(self):
        aisle = Aisle(name=self.request.get('aisleName'))
        aisle.put()
        self.redirect(settings.STORE_ROOT)

    def get(self):
        template_values = {

        }

        path = settings.TEMPLATE_DIR + "aisle/Add.html"
        self.response.out.write(template.render(path, template_values))

class EditAisleHandler(webapp.RequestHandler):
    def get(self):
        aisleKey = db.Key.from_path('Aisle',int(self.request.get('aisleKey')))
        aisle = db.get(aisleKey)
        
        template_values = {
            'currentName': aisle.name,
        }

        path = settings.TEMPLATE_DIR + "aisle/Edit.html"
        self.response.out.write(template.render(path, template_values))


class ManageAislesHandler(webapp.RequestHandler):
    def get(self):

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'


        template_values = {
            'basePath': '/aisle',
            'url': url,
            'url_linktext': url_linktext,
            'loadingHtml' : 'Loading...',
        }
        path = settings.TEMPLATE_DIR + "Manage.html"
        self.response.out.write(template.render(path, template_values))

class GetAllAislesHandler(webapp.RequestHandler):
    def get(self):
        aisles_query = Aisle.all().order('name')
        aisles = aisles_query.fetch(10)


        template_values = {
            'aisles': aisles,
        }


        path = settings.TEMPLATE_DIR + "aisle/List.html"
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [(settings.STORE_ROOT, ManageAislesHandler),
                                      (settings.STORE_ROOT + '/list', GetAllAislesHandler),
                                      (settings.STORE_ROOT + '/edit', EditAisleHandler),
                                      (settings.STORE_ROOT + '/add', AddAisleHandler)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
